use image::DynamicImage;
use imageproc::gradients::{horizontal_sobel, vertical_sobel};

/// 清晰度阈值 (Tenengrad梯度平均值)
const CLARITY_THRESHOLD: f32 = 50.0;

pub fn check_clarity(img: &DynamicImage) -> Result<f32, String> {
    // 转换为灰度图像
    let gray_img = img.to_luma8();

    // 计算水平和垂直方向的Sobel梯度
    let gx = horizontal_sobel(&gray_img);
    let gy = vertical_sobel(&gray_img);

    // 计算梯度幅值图像: sqrt(gx^2 + gy^2)
    let mut total: f32 = 0.0;
    for (x, y, pixel) in gx.enumerate_pixels() {
        let gx_val = pixel[0] as f32;
        let gy_val = gy.get_pixel(x, y)[0] as f32;
        let magnitude = (gx_val * gx_val + gy_val * gy_val).sqrt();
        total += magnitude;
    }

    // 计算平均梯度幅值
    let mean_magnitude = total / (gx.width() as f32 * gx.height() as f32);

    if mean_magnitude < CLARITY_THRESHOLD {
        Err(format!(
            "清晰度不足 (当前: {:.2}, 阈值: {})",
            mean_magnitude, CLARITY_THRESHOLD
        ))
    } else {
        Ok(mean_magnitude)
    }
}
